package com.km.wskj.itmonitor.pager.wq.note;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.cjj.SunFaceView;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlCallBack;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.wq.note.model.NoteBook;
import com.yydcdut.sdlv.Menu;
import com.yydcdut.sdlv.MenuItem;
import com.yydcdut.sdlv.SlideAndDragListView;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.util.GalleryHelper;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.StringUtils;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 笔记本列表
 */
public class NoteBookListActivity extends LActivity {
    private static final String TAG = "NoteBookListActivity";

    @BindView(R.id.slideListView)
    SlideAndDragListView slideListView;
    @BindView(R.id.tool_bar_back)
    ImageView toolBarBack;
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.tool_bar_right)
    ImageView toolBarRight;
    @BindView(R.id.materialRefreshLayout)
    MaterialRefreshLayout mMaterialRefreshLayout;

    //data
    List<NoteBook> noteBookList;
    //adapter
    MyAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note_book_list);
        ButterKnife.bind(this);

        toolBarTitle.setText("我的笔记本");
        toolBarBack.setVisibility(View.VISIBLE);
        toolBarRight.setVisibility(View.VISIBLE);
        toolBarRight.setImageResource(R.mipmap.add);

        initSwipeListView();
        //data
        loadNotebook();

        mMaterialRefreshLayout.setSunStyle(true);
        mMaterialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
                mMaterialRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadNotebook();
                    }
                }, 500);
            }

            @Override
            public void onfinish() {

            }
        });
    }

    private void showAddDlg(final NoteBook noteBook) {

        final EditText et = new EditText(this);
        et.setHint("输入笔记本名称");
        et.setTextColor(ContextCompat.getColor(context, R.color.text_dark));
        et.setTextSize(17.0f);
        et.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
        et.setPadding(16, 20, 16, 20);

        if (noteBook != null) {
            et.setText(noteBook.typeName);
        }
        AlertDialog dlg = new AlertDialog.Builder(context)
                .setTitle("添加笔记本")
                .setView(et)
                .setPositiveButton("确定"
                        , new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String input = et.getText().toString();
                                if (!StringUtils.isEmpty(input)) {
                                    NoteBook nb = new NoteBook();
                                    nb.typeName = input;

                                    if (noteBook != null) {
                                        nb.idX = noteBook.idX;
                                    }
                                    pdc.addNotebook(HTTP_TASK_TAG, nb.idX, nb.typeName, new ZxlCallBack() {
                                        @Override
                                        public Object parseNetworkResponse(Response response, int i) throws Exception {
                                            return null;
                                        }

                                        @Override
                                        public void onError(Call call, Exception e, int i) {
                                            if (noteBook == null) {
                                                errorToasty("添加失败", true);
                                            } else {
                                                errorToasty("保存失败", true);
                                            }
                                        }

                                        @Override
                                        public void onResponse(Object o, int i) {
                                            if (noteBook == null) {
                                                successToasty("添加成功", true);
                                            } else {
                                                successToasty("保存成功", true);
                                            }

                                            loadNotebook();
                                        }
                                    });
                                }
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).setCancelable(true).create();
        dlg.show();
    }

    @OnClick(R.id.action_note_text)
    public void onActionNoteText(View view) {
        if (noteBookList == null || noteBookList.size() == 0) {
            showAddDlg(null);
        } else {
            Intent t = new Intent(context, AddNoteActivity.class);
            startActivity(t);
        }
    }

    @OnClick(R.id.action_note_pic)
    public void onActionNotePic(View view) {
        if (noteBookList == null || noteBookList.size() == 0) {
            showAddDlg(null);
        } else {
            new GalleryHelper().openCamera(context, new GalleryHelper.OnPickPhotoCallback() {
                @Override
                public void onPickSucc(PhotoInfo photoInfo) {
                    String picpath = photoInfo.getPhotoPath();
                    Intent t = new Intent(context, AddNoteActivity.class);
                    t.putExtra("picpath", picpath);
                    startActivity(t);
                }

                @Override
                public void onPickFail(String s) {
                    errorToasty(s, true);
                }
            });
        }
    }

    private void loadNotebook() {
        pdc.noteBookList(HTTP_TASK_TAG, new ZxlGenericsCallback<List<NoteBook>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                mMaterialRefreshLayout.finishRefresh();
                errorToasty("获取笔记本失败", true);
            }

            @Override
            public void onResponse(List<NoteBook> o, int i) {
                successToasty("数据获取成功", true);
                noteBookList = o;
                adapter.notifyDataSetChanged();
                mMaterialRefreshLayout.finishRefresh();
            }
        });
    }

    private void initSwipeListView() {
        Menu menu = new Menu(true, false, 0);

        MenuItem item = new MenuItem.Builder()
                .setDirection(MenuItem.DIRECTION_RIGHT)
                .setText("删除")
                .setTextColor(ContextCompat.getColor(context, R.color.white))
                .setBackground(new ColorDrawable(ContextCompat.getColor(context, R.color.text_red)))
                .setWidth(200)
                .build();

        MenuItem item2 = new MenuItem.Builder()
                .setDirection(MenuItem.DIRECTION_RIGHT)
                .setText("修改")
                .setTextColor(ContextCompat.getColor(context, R.color.white))
                .setBackground(new ColorDrawable(ContextCompat.getColor(context, R.color.color_zy_blue)))
                .setWidth(200)
                .build();
        menu.addItem(item);
        menu.addItem(item2);

        slideListView.setMenu(menu);

        slideListView.setOnMenuItemClickListener(new SlideAndDragListView.OnMenuItemClickListener() {
            @Override
            public int onMenuItemClick(View v, final int itemPosition, int buttonPosition, int direction) {
                LogUtils.d("item position:" + itemPosition + " buttonpostion:" + buttonPosition);
                NoteBook nb = noteBookList.get(itemPosition);
                if (buttonPosition == 0) {
                    //del
                    pdc.delNoteBook(HTTP_TASK_TAG, nb.idX, new ZxlCallBack() {
                        @Override
                        public Object parseNetworkResponse(Response response, int i) throws Exception {
                            return null;
                        }

                        @Override
                        public void onError(Call call, Exception e, int i) {
                            errorToasty("删除笔记本出错" + e.getLocalizedMessage(), true);
                            LogUtils.e(TAG, e);
                        }

                        @Override
                        public void onResponse(Object o, int i) {
                            noteBookList.remove(itemPosition);
                            adapter.notifyDataSetChanged();
                        }
                    });
                } else {
                    //update
                    showAddDlg(nb);
                }
                return 0;
            }
        });
        slideListView.setOnListItemClickListener(new SlideAndDragListView.OnListItemClickListener() {
            @Override
            public void onListItemClick(View v, int position) {
                NoteBook nb = noteBookList.get(position);
                Intent t = new Intent(context, NoteListActivity.class);
                t.putExtra("nb", nb);
                startActivity(t);
            }
        });
        adapter = new MyAdapter();
        slideListView.setAdapter(adapter);

    }

    @OnClick({R.id.tool_bar_back, R.id.tool_bar_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tool_bar_back:
                finish();
                break;
            case R.id.tool_bar_right:
                showAddDlg(null);
                break;
        }
    }

    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (noteBookList != null) {
                return noteBookList.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return noteBookList.get(position);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            NoteBook nb = (NoteBook) getItem(position);
            BaseAdapterHelper helper = BaseAdapterHelper.get(context, convertView, parent, R.layout.item_note_book);
            helper.setText(R.id.tv_name, nb.typeName);
            helper.setText(R.id.tv_time, nb.createTime);
            return helper.getView();
        }
    }
}
